import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class MaterialAppExample extends StatefulWidget {
  const MaterialAppExample({Key? key}) : super(key: key);

  @override
  State<MaterialAppExample> createState() => _MaterialAppExampleState();
}

class _MaterialAppExampleState extends State<MaterialAppExample> {
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey();
  final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: _navigatorKey,
      scaffoldMessengerKey: _scaffoldMessengerKey,
      // home: Home(scaffoldMessengerKey: _scaffoldMessengerKey),
      routes: {
        '/Home': (_) => Home(
              scaffoldMessengerKey: _scaffoldMessengerKey,
            ),
        '/A': (_) => const A(),
        '/B': (_) => const B(),
        '/ErrorPage': (_) => const ErrorPage(),
      },
      initialRoute: '/A',
      onGenerateRoute: (settings) {
        if (kDebugMode) {
          print(settings.name);
          print(settings.arguments);
        }
        // return MaterialPageRoute(builder: (_) => const ErrorPage());
        return null;
      },
      // 没有路由表的时候使用这个
      onGenerateInitialRoutes: (initialRoute) {
        return [
          // MaterialPageRoute(builder: (_) => Home(scaffoldMessengerKey: _scaffoldMessengerKey)),
          MaterialPageRoute(builder: (_) => const A()),
          MaterialPageRoute(builder: (_) => const B()),
        ];
      },
      onUnknownRoute: (settings) {
        if (kDebugMode) {
          print('onUnknownRoute');
          print(settings.name);
          print(settings.arguments);
        }
        return MaterialPageRoute(builder: (_) => const ErrorPage());
      },
      navigatorObservers: [MyObserver()],
      // 当构建 Widget 前调用，主要用于字体大小、主题颜色等配置
      builder: (_, child) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('builder'),
          ),
          body: child,
        );
      },
      title: 'Flutter应用',
      onGenerateTitle: (_) {
        return '我的天';
      },
      color: Colors.yellow,
      theme: ThemeData(primarySwatch: Colors.red),
      darkTheme: ThemeData(primarySwatch: Colors.indigo),
      themeMode: ThemeMode.dark,
      highContrastTheme: ThemeData(primarySwatch: Colors.orange),
      highContrastDarkTheme: ThemeData(primarySwatch: Colors.teal),
      locale: const Locale('zh', 'CN'),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate, // 本地化委托
        // 代理类
        TestLocalizationsDelegate(),
      ],
      supportedLocales: const [
        Locale('en', 'US'), //美国英语
        Locale('zh', 'CN'), //中文简体
      ],
      localeListResolutionCallback:
          (List<Locale>? locales, Iterable<Locale> supportedLocales) {
        if (kDebugMode) {
          print('===localeListResolutionCallback');
          print(locales);
          print(supportedLocales);
        }
        // 系统切换语言时调用
        return Locale('zh', 'CN');
      },
      localeResolutionCallback:
          (Locale? locales, Iterable<Locale> supportedLocale) {
        if (kDebugMode) {
          print('===localeResolutionCallback');
          print(locales);
          print(supportedLocale);
        }
        // 系统切换语言时调用
        return Locale('zh', 'CN');
      },
      debugShowMaterialGrid: false, // 在 debug 模式下展示基线网格
      // showPerformanceOverlay: true, // 开启帧率性能叠加
      // checkerboardRasterCacheImages: true, // 打开栅格缓存图像的棋盘格
      // checkerboardOffscreenLayers: true, // 打开渲染到屏幕外位图的层的棋盘格
      // showSemanticsDebugger: true, // 打开显示可访问性信息的叠加层，展示组件之间的关系、占位大小
      // debugShowCheckedModeBanner: false, // 右上角是否显示一个 debug 的横幅
    );
  }
}

class MyObserver extends NavigatorObserver {
  @override
  void didPush(Route route, Route? previousRoute) {
    if (kDebugMode) {
      print('MyObserver');
      print(route);
      print(previousRoute);
    }
    super.didPush(route, previousRoute);
  }
}

class Home extends StatelessWidget {
  const Home({
    Key? key,
    required GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey,
  })  : _scaffoldMessengerKey = scaffoldMessengerKey,
        super(key: key);

  final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('demo'),
            TextButton(
              onPressed: () {
                Navigator.pushNamed(context, '/A');
              },
              child: const Text('PUSH A'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pushNamed(context, '/B');
              },
              child: const Text('PUSH B'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // showDialog(context: context, builder: (_) => const AlertDialog(title: Text("title")));
          // showDialog(context: _navigatorKey.currentState!.overlay!.context, builder: (_) => const AlertDialog(title: Text("title")));
          _scaffoldMessengerKey.currentState!.showSnackBar(
            const SnackBar(content: Text('scaffoldMessengerKey')),
          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

class A extends StatefulWidget {
  const A({Key? key}) : super(key: key);

  @override
  State<A> createState() => _AState();
}

class _AState extends State<A> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('A page')),
      body: Center(
        child: TextButton(
          onPressed: () {
            Navigator.pushNamed(context, '/B');
          },
          child: const Text('A PAGE PUSH B'),
        ),
      ),
    );
  }
}

class B extends StatefulWidget {
  const B({Key? key}) : super(key: key);

  @override
  State<B> createState() => _BState();
}

class _BState extends State<B> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('B page')),
      body: Center(
        child: TextButton(
          onPressed: () {
            Navigator.pushNamed(context, '/AB');
          },
          child: Text('B PAGE PUSH A ${TestLocalizations.of(context).title}'),
        ),
      ),
    );
  }
}

class ErrorPage extends StatefulWidget {
  const ErrorPage({Key? key}) : super(key: key);

  @override
  State<ErrorPage> createState() => _ErrorPageState();
}

class _ErrorPageState extends State<ErrorPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ERROR page')),
      body: Center(
        child: TextButton(
          onPressed: () {
            Navigator.pushNamed(context, '/A');
          },
          child: const Text('ERROR PAGE PUSH A'),
        ),
      ),
    );
  }
}

class TestLocalizations {
  TestLocalizations(this.isZh);

  bool isZh = false;

  /// 方便获取静态方法
  static TestLocalizations of(BuildContext context) {
    return Localizations.of<TestLocalizations>(context, TestLocalizations)!;
  }

  /// 获取标题
  String get title {
    return isZh ? 'Material 示例工程' : 'Material Example';
  }
}

/// 代理类
class TestLocalizationsDelegate
    extends LocalizationsDelegate<TestLocalizations> {
  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);

  /// 加载对应locale子类
  @override
  Future<TestLocalizations> load(Locale locale) {
    return SynchronousFuture<TestLocalizations>(
        TestLocalizations(locale.languageCode == 'zh'));
  }

  @override
  bool shouldReload(covariant LocalizationsDelegate old) => false;
}
